package net.diaowen.dwsurvey.service.impl;

import com.alibaba.fastjson.JSON;
import net.diaowen.common.base.entity.User;
import net.diaowen.common.enums.SurveyTodoTaskStatusEnum;
import net.diaowen.common.service.BaseServiceImpl;
import net.diaowen.common.utils.HttpJsonUtil;
import net.diaowen.common.utils.LogUtils;
import net.diaowen.common.utils.ResponseResult;
import net.diaowen.dwsurvey.dao.SurveyDirectoryDao;
import net.diaowen.dwsurvey.dao.SurveyTodoTaskDao;
import net.diaowen.dwsurvey.entity.SurveyDirectory;
import net.diaowen.dwsurvey.entity.SurveyTodoTask;
import net.diaowen.dwsurvey.service.SurveyDirectoryManager;
import net.diaowen.dwsurvey.service.SurveyTodoTaskManager;
import net.diaowen.dwsurvey.vo.AddTodoTaskVO;
import net.diaowen.dwsurvey.vo.FinishTodoTaskVO;
import net.diaowen.dwsurvey.vo.TaskHiMessageSimpleDTO;
import net.diaowen.dwsurvey.vo.TaskMessageSimpleDTO;
import org.apache.commons.collections.CollectionUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 问卷代办
 */
@Service("surveyTodoTaskManager")
public class SurveyTodoTaskManagerImpl extends BaseServiceImpl<SurveyTodoTask, String> implements SurveyTodoTaskManager {

    public static final String BASE_URI = "http://192.168.5.103:6060";
    public static final String START_TODO_TASK_URL = "/todo/sendTodoTaskSimple";
    public static final String END_TODO_TASK_URL = "/todo/sendDoTaskSimple";

    @Autowired
    private SurveyTodoTaskDao surveyTodoTaskDao;
    @Autowired
    private SurveyDirectoryDao surveyDirectoryDao;

    @Override
    public void setBaseDao() {
        this.baseDao = surveyTodoTaskDao;
    }

    @Transactional
    public void saveByAdmin(AddTodoTaskVO addTodoTaskVO, User curUser) {
//        Criterion eqId = Restrictions.eq("id", addTodoTaskVO.getSurveyDirectoryId());
//        SurveyDirectory surveyDirectory = surveyDirectoryDao.findUnique(eqId);
        SurveyDirectory surveyDirectory = surveyDirectoryDao.get(addTodoTaskVO.getSurveyDirectoryId());
        if (surveyDirectory==null) {
            return;
        }
        List<SurveyTodoTask> surveyTodoTaskList = addTodoTaskVO.getAssigneeList().stream().map(x -> {
            SurveyTodoTask surveyTodoTask = new SurveyTodoTask();
            surveyTodoTask.setAssigneeType(addTodoTaskVO.getType());
            surveyTodoTask.setAssigneeCode(x.getAssigneeCode());
            surveyTodoTask.setAssigneeName(x.getAssigneeName());

//			surveyTodoTask.setOwnerType("user");
//			surveyTodoTask.setOwnerName("admin");
//			surveyTodoTask.setOwnerCode("-1000");
            surveyTodoTask.setSurveyDirectoryId(addTodoTaskVO.getSurveyDirectoryId());
            surveyTodoTask.setState(SurveyTodoTaskStatusEnum.UNSTARTED.getValue());
//			surveyTodoTask.setStartTime(new Date());
//			surveyTodoTask.setEndTime(null);
//			surveyTodoTask.setCreateTime(new Date());
//			surveyTodoTask.setUpdateTime(new Date());
            surveyTodoTask.setSurveyDirectoryName(surveyDirectory.getSurveyName());
            surveyTodoTask.setSurveyDirectorySid(surveyDirectory.getSid());
            surveyTodoTask.setSurveyDirectoryUrl("http://192.168.5.106:8080/static/diaowen/answer-p.html?sid="+surveyDirectory.getSid());
            return surveyTodoTask;
        }).collect(Collectors.toList());
        surveyTodoTaskDao.saveAll(surveyTodoTaskList);
    }

    @Override
    public void finish(FinishTodoTaskVO finishTodoTaskVO) {
        Criterion criterion1 = Restrictions.eq("surveyDirectoryId", finishTodoTaskVO.getSurveyDirectoryId());
        Criterion criterion2 = Restrictions.eq("state", SurveyTodoTaskStatusEnum.STARTED.getValue());
        SurveyTodoTask surveyTodoTask = surveyTodoTaskDao.findUnique(criterion1, criterion2);
        if (surveyTodoTask == null) {
            return;
        }
        surveyTodoTask.setState(SurveyTodoTaskStatusEnum.FINISH.getValue());
        surveyTodoTaskDao.save(surveyTodoTask);
    }

    @Override
    public void startTodoTask() {
        // 1.筛选未发起代办的事项
        Criterion criterion = Restrictions.eq("state", SurveyTodoTaskStatusEnum.UNSTARTED.getValue());
        List<SurveyTodoTask> surveyTodoTaskList = surveyTodoTaskDao.find(criterion);
        if (CollectionUtils.isEmpty(surveyTodoTaskList)) {
            return;
        }
        // TODO 2.发起代办
        try {
            List<TaskMessageSimpleDTO> params = buildStartTodoTaskParams(surveyTodoTaskList);
            ResponseResult result = HttpJsonUtil.post(BASE_URI + START_TODO_TASK_URL, params, ResponseResult.class);
            if (!result.getCode().equals(ResponseResult.SUCCESS_CODE)) {
                return;
            }
            // 3.更新状态机
            for (SurveyTodoTask surveyTodoTask : surveyTodoTaskList) {
                surveyTodoTask.setState(SurveyTodoTaskStatusEnum.STARTED.getValue());
            }
            surveyTodoTaskDao.saveAll(surveyTodoTaskList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<TaskMessageSimpleDTO> buildStartTodoTaskParams(List<SurveyTodoTask> surveyTodoTaskList) {
        List<TaskMessageSimpleDTO> params = surveyTodoTaskList.stream().map(x -> {
            TaskMessageSimpleDTO task = new TaskMessageSimpleDTO();
            task.setTaskId(x.getSurveyDirectoryId());
            task.setTaskName("数据收集代办");
            task.setType(x.getAssigneeType());
//            task.setOwnerId(x.getOwnerCode());
//            task.setOwnerName("admin");
            task.setAssigneeId(x.getAssigneeCode());
            task.setAssigneeName(x.getAssigneeName());
//            task.setTaskDueTime(null);

            task.setTaskSource(x.getSurveyDirectoryUrl());
            return task;
        }).collect(Collectors.toList());
        return params;
    }

    @Override
    public void endTodoTask() {
        // 1.筛选可以完成代办的事项
        Criterion criterion = Restrictions.eq("state", SurveyTodoTaskStatusEnum.FINISH.getValue());
        List<SurveyTodoTask> surveyTodoTaskList = surveyTodoTaskDao.find(criterion);
        if (CollectionUtils.isEmpty(surveyTodoTaskList)) {
            return;
        }
        // 2.完成代办
        for (int i = 0; i < surveyTodoTaskList.size(); i++) {
            doEndTodoTask(surveyTodoTaskList.get(i));
        }
    }

    private void doEndTodoTask(SurveyTodoTask surveyTodoTask) {
        try {
            // 1.组装参数
            TaskHiMessageSimpleDTO params = buildEndTodoTaskParams(surveyTodoTask);
            // 2.发送请求
            ResponseResult result = HttpJsonUtil.post(BASE_URI + END_TODO_TASK_URL, params, ResponseResult.class);
            if (!result.getCode().equals(ResponseResult.SUCCESS_CODE)) {
                LogUtils.op("完成代办").kv("result", result.getResult()).info();
                return;
            }
            // 3.更新状态机
            surveyTodoTask.setState(SurveyTodoTaskStatusEnum.CLOSED.getValue());
            surveyTodoTaskDao.save(surveyTodoTask);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private TaskHiMessageSimpleDTO buildEndTodoTaskParams(SurveyTodoTask surveyTodoTask) {
        TaskHiMessageSimpleDTO task = new TaskHiMessageSimpleDTO();
        task.setTaskId(surveyTodoTask.getSurveyDirectoryId());
        return task;
    }
}
